<?php
/**
 * Created by PhpStorm.
 * User: asus
 * Date: 2018/2/28
 * Time: 15:34
 */

namespace app\index\business;
use app\index\business\BaseBusiness;
use app\libs\HxSms;
use app\libs\Predis;
use app\libs\SendSms;
use think\Config;

class Mobile extends BaseBusiness
{
    const KEY_SMS = 'qc_sms';

    public $redis = null;

    public function __construct()
    {
        $this->redis = new Predis();
    }
    public function sendSms($data){
        // 如果发过了需要一分钟后再发
        $key_time = self::KEY_SMS.':type:'.$data['type'].':phone:'.$data['phone'].':time';
        $ttl = $this->redis->get($key_time);

        if ($ttl){
            $this->result['status'] = -1;
            $this->result['msg'] = '验证码已发送请勿频繁请求';
            return $this->result;
        }
        $smsObj = new HxSms();
        $sms_code = $this->getSms($data['type'],$data['phone']);

        if ($sms_code){
            $value = $sms_code;
        }else{
            // 过期了
            $value = rand(1000,9999);
        }
        $sms_result = $smsObj ->send($data['phone'],$value);
        $sms_result=json_decode($sms_result,true);
        if ($sms_result['returnstatus'] !== 'Success'){
           $this->result['status'] = -1;
           $this->result['msg'] = $sms_result['message'];
           return $this->result;
        }
        // 计入缓存
        $key = self::KEY_SMS.':type:'.$data['type'].':phone:'.$data['phone'];
        $key_time = self::KEY_SMS.':type:'.$data['type'].':phone:'.$data['phone'].':time';
        $this->redis->set($key_time,1,Config::get('mobile_code.left_time'));
        $this->redis->set($key,$value,Config::get('mobile_code.exp_time'));

        $this->result['status'] = 1;
        $this->result['msg'] = '发送成功';
        $this->result['data'] ['code'] = $value;

        return $this->result;
    }
    public function getSms($type,$phone){
        $key = self::KEY_SMS.':type:'.$type.':phone:'.$phone;
        $sms = $this->redis->get($key);
        if(!$sms){
            return false;
        }
        return $sms;
    }

    public function checkPhoneCode($phone,$code,$type){
        $key_time = $key = self::KEY_SMS.':type:'.$type.':phone:'.$phone. ':time';
        $time = (int)$this->redis->get($key_time);
        if ($time>3){
            // 清楚code
            $this->delSms($type,$phone);
            return 2;
        }

        $key = self::KEY_SMS.':type:'.$type.':phone:'.$phone;
        $sms = $this->redis->get($key);
        if (!$sms){
            return false;
        }
        if ($sms != $code){
            $new_time = $time + 1;
            $this->redis->set($key_time,$new_time,Config::get('mobile_code.error_time'));
            return false;
        }
        return true;
    }

    public function delSms($type,$phone){
        $key = self::KEY_SMS.':type:'.$type.':phone:'.$phone;
        $this->redis->del($key);
    }

    public function sendPhoneSms($user_no,$token_password,$reqData){
        //查询该用户是否已设置手机
        $filed = ['phone'];
        $userInfo = $this->getBusiness('RedisCache')->getUserInfo($user_no,$token_password,$filed);
        if(!$userInfo){
            $this->result['status'] = -1;
            $this->result['msg'] = 'login_expire';
            return $this->result;
        }

        if($reqData['type'] == 1){
            if($userInfo['phone'] != ''){
                $this->result['status'] = -1;
                $this->result['msg'] = 'phone_exit';
                return $this->result;
            }
        }elseif($reqData['type'] == 2){
            if($userInfo['phone'] == ''){
                $this->result['status'] = -1;
                $this->result['msg'] = 'phone_not_exit';
                return $this->result;
            }
        }else{
            $this->result['status'] = -1;
            $this->result['msg'] = 'phone_type_error';
            return $this->result;
        }

        if($reqData['type'] == 2){
            //解绑
            //根据user_no查询手机号
            $reqData['phone'] = $userInfo['phone'];
        }elseif($reqData['type'] == 1){
            //判断手机号的唯一性
            $phone = $this->getBusiness('User')->getByPhone($reqData['phone']);
            if($phone){
                $this->result['status'] = -1;
                $this->result['msg'] = 'phone_exit_uno';
                return $this->result;
            }
        }


        //redis查询该手机号码的验证码是否还有有效值
        $sms = $this->getSms($user_no,$reqData['type'],$reqData['phone']);
        if(!$sms){
            $sms_code = mt_rand(100000,999999);
        }else{
            $sms_code = $sms;
        }

        //将短信数据存储到redis 和 数据库
        $sendSmsData['user_no'] = $user_no;
        $sendSmsData['phone'] = $reqData['phone'];
        $sendSmsData['code'] = $sms_code;
        $sendSmsData['type'] = $reqData['type'];
        $sendSms = $this->getModel('Mobile')->saveMobile($sendSmsData);
        if(!$sendSms){
            $this->result['status'] = -1;
            $this->result['msg'] = 'send_sms_fail';
            return $this->result;
        }

        //发送短信（存储redis）
        $this->sendSms($user_no,$reqData['type'],$reqData['phone'],$sms_code);

        //根据header获取语言
        $lang = $this->request->getHeader('lang');

        //发送短息（sendsms）
        $this->sendPhone($reqData['phone'],$lang,'code',$sms_code);

        $this->result['status'] = 1;
        $this->result['msg'] = 'send_sms_success';
        return $this->result;
    }

    public function checkPhoneSms($user_no,$token_password,$reqData){
        if($reqData['type'] == 2){
            //解绑
            //根据user_no查询手机号
            $filed = ['phone'];
            $user = $this->getBusiness('RedisCache')->getUserInfo($user_no,$token_password,$filed);
            $reqData['phone'] = $user['phone'];
        }elseif($reqData['type'] == 1){
            //判断手机号的唯一性
            $phone = $this->getBusiness('User')->getByPhone($reqData['phone']);
            if($phone){
                $this->result['status'] = -1;
                $this->result['msg'] = 'phone_exit_uno';
                return $this->result;
            }
        }

        //判断验证码是否正确(true:正确 false：失败 2：次数过多)
        $checkPhone = $this->checkSms($user_no,$reqData['type'],$reqData['phone'],$reqData['code']);
        if(!$checkPhone){
            $this->result['status'] = -1;
            $this->result['msg'] = 'sms_code_error';
            return $this->result;
        }

        if($checkPhone === 2){
            $this->result['status'] = -1;
            $this->result['msg'] = 'sms_code_time_more';
            return $this->result;
        }

        //同步数据库 和 redis
        if($reqData['type'] == 1){
            //绑定
            $data['phone'] = $reqData['phone'];
            $addPhone = $this->getBusiness('User')->updateByUserNo($user_no,$data);
            if(!$addPhone){
                $this->result['status'] = -1;
                $this->result['msg'] = 'add_phone_fail';
                return $this->result;
            }

            $this->getBusiness('RedisCache')->setUserInfo($user_no,$token_password,$data);

            $msg = 'add_phone_success';
        }elseif($reqData['type'] == 2){
            //解绑
            $data['phone'] = '';
            $addPhone = $this->getBusiness('User')->updateByUserNo($user_no,$data);
            if(!$addPhone){
                $this->result['status'] = -1;
                $this->result['msg'] = 'del_phone_fail';
                return $this->result;
            }

            $this->getBusiness('RedisCache')->setUserInfo($user_no,$token_password,$data);

            $msg = 'del_phone_success';
        }else{
            $this->result['status'] = -1;
            $this->result['msg'] = 'phone_type_error';
            return $this->result;
        }

        $this->delSms($reqData['type'],$reqData['phone']);

        $this->result['status'] = 1;
        $this->result['msg'] = $msg;
        return $this->result;
    }


    //phone:手机 lang：语言 param：状态 code：信息
    public function sendPhone($data){
        //判断语言
        if($lang == 'zh-CN'){
            $language = 'cn';
        }else{
            $language = 'en';
        }

        //判断是否是国籍手机
        $phoneLenth = strlen($phone);
        if($phoneLenth < 11){
            $area = 'english';
        }else{
            $area = 'china';
        }

        $sms = [];
        $templateId = [];
        switch ($param){
            case 'login':
                $templateId['china']['cn'] = '14574';
                $templateId['china']['en'] = '15368';
                $templateId['english']['cn'] = '15455';
                $templateId['english']['en'] = '15460';
                break;
            case 'code':
                $templateId['china']['cn'] = '14733';
                $templateId['china']['en'] = '15437';
                $templateId['english']['cn'] = '15459';
                $templateId['english']['en'] = '15464';
                break;
        }

        $sms['templateId'] = $templateId[$area][$language];
        $sms['phone'] = $phone;
        $sms['code'] = $code;
        $SendSms = new SendSms();
        $SendSms->send_sms($sms);
    }
}